<script lang="ts" setup>
import { getMap, toInitial } from '@/map'
import { nextTick, onBeforeUnmount } from 'vue'
import type { Ref } from 'vue'
import { Map, Feature, MapBrowserEvent } from 'ol'
import VectorLayer from 'ol/layer/Vector'
import VectorSource from 'ol/source/Vector'
import { Point, SimpleGeometry } from 'ol/geom'
import { Style, Circle as CircleStyle } from 'ol/style'
import Fill from 'ol/style/Fill'
import Stroke from 'ol/style/Stroke'
import { useMessage } from 'naive-ui'
// 
const message = useMessage()
const map_ = getMap()?.map as Ref<Map | null>
const xc = [114.86933826966052, 33.46835219138212]
const home = [114.96412725187491,33.397944360814684]
const markerLayer = new VectorLayer({
    source: new VectorSource({
        wrapX: false
    }),
    properties: {
        name: "TEST_POINT"
    }
})
const pointFeature = new Feature({
    geometry: new Point([xc[0], xc[1]]), // 使用经纬度坐标创建点要素
    name: '散点1' // 添加其他属性到要素中
    , title: "项城市"
})
pointFeature.setStyle(new Style({
    image: new CircleStyle({
        radius: 6, // 散点的半径
        fill: new Fill({
            color: 'green' // 散点的填充颜色
        }),
        stroke: new Stroke({
            color: 'green', // 散点的边框颜色
            width: 2 // 散点的边框宽度
        })
    })
}))
const homeFeature = new Feature({
    geometry: new Point(home), // 使用经纬度坐标创建点要素
    name: 'dgdte' // 添加其他属性到要素中
    , title: "家"
})
homeFeature.setStyle(new Style({
    image: new CircleStyle({
        radius: 3, // 散点的半径
        fill: new Fill({
            color: 'green' // 散点的填充颜色
        }),
        stroke: new Stroke({
            color: 'green', // 散点的边框颜色
            width: 2 // 散点的边框宽度
        })
    })
}))
markerLayer.getSource()?.addFeatures([pointFeature,homeFeature])
const singleclickHandler = (event: MapBrowserEvent<any>) => {
    toInitial(map_).forEachFeatureAtPixel(event.pixel, (feature, layer, geometry) => {
        console.log('click', { feature, layer, geometry });
        message.success(`${feature.get("title")} 的坐标： ${(geometry as SimpleGeometry).getCoordinates()}`)

    }, {
        layerFilter: (layer) => layer.get("name") === "TEST_POINT"
    })
}
onBeforeUnmount(() => {
    const map = toInitial(map_) as Map
    map.un('singleclick', singleclickHandler)
    markerLayer.getSource()?.clear()
    map.removeLayer(markerLayer)
})
nextTick(() => {
    const map = toInitial(map_) as Map
    map.addLayer(markerLayer)
    map.on('singleclick', singleclickHandler)
    // map.on('singleclick', (event: MapBrowserEvent<any>) => {
    //     message.success(`坐标： ${event.coordinate}`)
    // })
})




</script>
<template>
    <!-- <div class="map_controls">
        标记点
    </div> -->
</template>